﻿namespace Arms.Presentation.Web
{
    using Arms.Application.Modules.Security;
    using Arms.Framework.Security;
    using Arms.Presentation.Web.App_Start;
    using Arms.Presentation.Web.Models;
    using Arms.Presentation.Web.Models.Shared;
    using Newtonsoft.Json;
    using System;
    using System.Web;
    using System.Web.Http;
    using System.Web.Mvc;
    using System.Web.Routing;
    using System.Web.Security;

    public class MvcApplication : HttpApplication
    {

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            RegisterModelBinders(ModelBinders.Binders);

        }

        public static void RegisterModelBinders(ModelBinderDictionary binders)
        {
            binders.Add(typeof(ProductPickerModel), new ProductPickerBinder());
        }

        protected void Application_AcquireRequestState(object sender, EventArgs e)
        {
            if (Request.IsAuthenticated && !Request.Url.AbsoluteUri.Contains(".axd"))
            {
                HttpContext.Current.User = NinjectWebCommon.Resolve<IUser>();
            }
        }

        protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            if (Request.IsAuthenticated && !Request.Url.AbsoluteUri.Contains(".axd"))
            {
                if ((HttpContext.Current.User as ArmsUser) == null)
                {
                    var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                    if (authCookie == null) return;

                    // extract the forms authentication cookie
                    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                    if (authTicket == null) return;

                    if (string.IsNullOrWhiteSpace(authTicket.UserData)) return;

                    // extract user data from ticket
                    var model = JsonConvert.DeserializeObject<ArmsUserData>(authTicket.UserData);
                    if (model != null && model.HasIdentity)
                    {
                        // ArmsUser implements IPrincipal
                        var newUser = new ArmsUser(Context.User.Identity)
                        {
                            UserID = model.UserID,
                            UserClassID = model.UserClassID,
                            UserName = model.UserName
                        };
                        NinjectWebCommon.Kernel.Rebind<IUser>().ToMethod(x => newUser);
                        Context.User = newUser;
                    }
                }
            }
        }
    }
}